from typing import List, Dict


class Interaction:
    def __init__(self, item_id, user_id, interaction_type=0, info=None, extra_info=None):
        self.item_id = item_id
        self.user_id = user_id
        self.interaction_type = interaction_type  # 0: Reader
        self.info = info
        self.extra_info = extra_info


class FileLoader:
    def __init__(self, hyper_params):
        self.filename = hyper_params['dataset_path']
        self.book = {}
        self.reader = {}
        self.intereaction_list: Dict[int, List[int]] = {}
        self.book_cnt = 0
        self.reader_cnt = 0

        self.read_from_dataset_file()
        hyper_params['item_cnt'] = self.book_cnt
        hyper_params['user_cnt'] = self.reader_cnt

    def read_from_dataset_file(self):
        with open(self.filename, encoding='utf-8', errors='ignore') as file_object:
            for line in file_object:
                words = line.split('@')
                if len(words) > 7 and not words[7].startswith('518'):
                    continue

                if '50' in words:  # only use borrow cases
                    # use ID and book name as key
                    bookKey = words[0] + '@' + words[1]
                    if bookKey not in self.book:
                        self.book[bookKey] = self.book_cnt
                        self.book_cnt = self.book_cnt + 1

                    readerKey = words[7]  # use student ID as key
                    if readerKey not in self.reader:
                        self.reader[readerKey] = self.reader_cnt
                        self.reader_cnt = self.reader_cnt + 1

                    cur_book_id = self.book[bookKey]
                    cur_reader_id = self.reader[readerKey]

                    if cur_reader_id not in self.intereaction_list:
                        self.intereaction_list[cur_reader_id] = []

                    self.intereaction_list[cur_reader_id].append(
                        Interaction(cur_book_id, cur_reader_id))

        print(
            f'Reader: {self.reader_cnt}, Book: {self.book_cnt}, Interact: {len(self.intereaction_list)}')


if __name__ == '__main__':
    hyper_params = {
        'dataset_path': 'datasets/lib.txt'
    }

    file_loader = FileLoader(hyper_params=hyper_params)
    print(
        f'Reader: {file_loader.reader_cnt}, Book: {file_loader.book_cnt}, Interact: {len(file_loader.intereaction_list)}')
